﻿using OA.IService;
using OA.ViewModels.Account;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace OA.UI.MVC.Controllers
{
    public class AccountController : Controller
    {

        public ISysUserService  userService{ get; set; }

       
        [HttpGet]
        [AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<ActionResult> Index(LoginViewModel model,string ReturnUrl="")
        {
            if (ModelState.IsValid)
            {
                var user = await userService.GetList(u=>u.LoginName==model.LoginName && u.LoginPwd==model.LoginPwd)
                    .Include(u=>u.Roles) .FirstOrDefaultAsync();

                var userdata=user.Roles.Select(r=>r.Id.ToString()).ToArray();

                if (user!=null)
                {
                    // 保存登录状态
                    //FormsAuthentication.SetAuthCookie(model.LoginName, false);

                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,   // 版本号
                        model.LoginName,   // 用户名
                        DateTime.Now,   // 颁发时间
                        DateTime.Now.AddMinutes(20),   // 失效时间点
                        false,   // 是否永久
                        string.Join(",",userdata)  // 自定义数据   "1,2,3"
                        );

                    var val=FormsAuthentication.Encrypt(ticket); // 加密

                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, val);
                    cookie.Expires= DateTime.Now.AddMinutes(20);

                    Response.Cookies.Add(cookie); // 将cookie写入客户端

                    if (ReturnUrl.Length> 0)
                    {
                        return Redirect(ReturnUrl);
                    }
                    return RedirectToAction("index", "home");
                }
                else
                {
                    ModelState.AddModelError("", "账号或密码错误！");
                }
            }
            return View(model);
        }

    }
}